//index.js
//获取应用实例
var app = getApp()
var QQMapWX = require('../../../resource/js/qqmap-wx-jssdk.min.js');
var qqmapsdk;
Page({
	data: {
		root:'',
		siteroot:app.setting.siteroot,
		att_url:app.setting.att_url,
		action:"/goods.detail/",
		account:app.setting.account,
		showtype:0,
		showtopnav:false,
		showtotop:false,
		showhuodong:false,
		modal_address:false,
		showspec:false,
		loading:true,
		pcd: ['广东省', '广州市', '海珠区'],
		pagetitle:'商品详情' + '-' + app.setting.title,
		nodata_pic:'../core/resource/images/goods_nodata.jpg'
		
	},
	onReady: function (){
	},
	onPullDownRefresh: function (){
		var the=this;
		var opt={};
		the.onLoad(opt);
		setTimeout(function(){
			wx.stopPullDownRefresh()
		},1000);
	},
	onLoad: function (opt){
		var page=this;
		var loading=page.data.loading
		wx.setNavigationBarTitle({'title':page.data.pagetitle});
		var route=page.route;
		page.setData({
			route:route,
		});
		if(opt.isgoshare){
				page.setData({
					ShowGoshare:true,
				});
		}
		if(opt.fromuser){
			var path=route.slice(0,-6).split('/');
			app.access.plugin=path.shift();
			app.access.action=path.join('.');
			app.access.query =app.util.made_query(opt,true);
			app.access.op=opt.op?opt.op:'';
		}
		//来自直播的参数
		if(opt.room_id){
			var path=route.slice(0,-6).split('/');
			app.access.plugin=path.shift();
			app.access.action=path.join('.');
			app.access.query =app.util.made_query(opt,true);
			app.access.op=opt.op?opt.op:'';
		}
		app.access.query += '&newapp=1';
		app.util.get(app.access,function(pagedata){
			console.log('goods');console.log(pagedata);
			if(pagedata.goods && pagedata.goods.content){
				pagedata.goods.content=pagedata.goods.content.replace(/\<img/gi, '<img style="max-width:100%"' );
			}
			var roomsurl='plugin-private://'+app.live_appid+'/pages/live-player-plugin?room_id='+pagedata.roomsid;
			page.setData({
				pagedata:pagedata,
				action:"goods.index/",
				roomsurl:roomsurl,
				nodatapic_close:true,
				loading:false
			});
			page.endDown(pagedata.goods.active.rest_time2);
			page.GetImagetmp(pagedata);
			page.getcomments(1);
			page.get_hot_goods();
			app.util.location(function(res){
					var lat_lng={lat:res.latitude,lng:res.longitude}
					page.setData({
						lat_lng:lat_lng
					});
					page.getstores(lat_lng);
			});		
		});
	},
	onShow: function (){
		var the=this;
		var pagedata=the.data.pagedata
		if(pagedata && pagedata.goods && pagedata.goods.active && pagedata.goods.active.rest_time){
			the.getactive();
		}
	},
	getactive:function(){
		var the=this;
		var pagedata=the.data.pagedata
		app.util.get('jy_weishop/goods.detail/getactive/goods_id='+pagedata.goods.id+'&active_id='+pagedata.goods.active_id+'&active_plugin='+pagedata.goods.active_plugin,function(res){
			//console.log('goods');console.log(pagedata);
			the.setData({
				'pagedata.goods.active':res.active,
			});
			the.endDown(res.active.rest_time2);
		});
	},
	onPageScroll:function (e) { // 获取滚动条当前位置
		var showtopnav=this.data.showtopnav
		var showtotop=this.data.showtotop
      if (e.scrollTop > 100 && !showtopnav) {
        this.setData({
          showtopnav: true,
        })
      }
	  if(e.scrollTop < 100 && showtopnav){
		this.setData({
          showtopnav: false
        })  
	  }
	  if (e.scrollTop > 700 && !showtotop) {
        this.setData({
          showtotop: true
        })
      }
	  if(e.scrollTop < 700 && showtotop){
		this.setData({
          showtotop: false
        })  
	  }
	},
	onReachBottom:function(){
		this.setData({
          showtop: 1
        }) 
	},
	showtype:function(e){
		var page=this
		var pagedata = this.data.pagedata
		var showtype=e.currentTarget.dataset.showtype
		if(showtype==1){
			wx.pageScrollTo({
			  selector: '#goodscontent',
			  duration: 300
			})
			page.setData({
				showtype:0,
				isgoodscontent:true
			});
			return true;
		}
		if(showtype==0){
			wx.pageScrollTo({
			  selector: '#index',
			  duration: 300
			})
			page.setData({
				showtype:0,
				isgoodscontent:false
			});
			return true;
		}
		if(showtype==3){
			page.getcomments();
		}
		page.setData({
				showtype:showtype,
				isgoodscontent:false
		});
	},
	//翻页
	onReachBottom: function () {
		var the=this;
		var isnodata=this.data.isnodata
		var loading=this.data.loading
		if(!isnodata && !loading && the.data.showtype==3){
			this.getcomments()
		}
	},
	getstores: function (lat_lng){
		var page=this;
		var pagedata=page.data.pagedata
		var id=pagedata.goods.id;
		app.util.post('jy_weishop/get_data/getstores/',{'lat_lng':lat_lng,'id':id},function(res){
			console.log('getstores');console.log(res);
			pagedata.post.storeid = res.stores[0].id;
			page.setData({
				'pagedata.stores':res.stores,
				'pagedata.stores_count':res.stores_count,
				'pagedata.post':pagedata.post,
				'pagedata.selectstore':res.stores[0],
			});
		});
	},
	get_hot_goods: function (){
		var page=this;
		app.util.get('jy_weishop/get_data/gethot_goods/',function(res){
			//console.log('coupon');console.log(pagedata);
			page.setData({
				'pagedata.hot_list':res.list,
			});
		});
	},
	getcomments:function(e){
		var the=this;
		var page = the.data.page
		var pagedata=the.data.pagedata
		var isnodata = the.data.isnodata
		pagedata.params = pagedata.params?pagedata.params:{}
		if(e){
			if(e.currentTarget){
				var data=e.currentTarget.dataset;
				if(data.type){
					pagedata.params.type=data.type;
					pagedata.comments_type=data.type;
					the.setData({
						'pagedata.comments_type':data.type
					});
				}
			}
			page = 1;
			pagedata.comments=[];
			isnodata=false;
		}else{
			if(isnodata){
				return false;
			}
		}
		var query='page='+page;
		var more_query=app.util.made_query(pagedata.params);
		if(more_query){
			query+='&'+more_query;
		}
		//console.log('query');console.log(query);
		app.util.get('jy_weishop/goods.detail/getcomments/'+query,function(res){
			//console.log('getcomments');console.log(res);
			if(res=='none'){
				the.setData({
					isnodata:true,
					'pagedata.comments':pagedata.comments,
					loading:false,
				});
			}else{
				pagedata.comments = pagedata.comments.concat(res.list)
				page++
				the.setData({
					'pagedata.comments':pagedata.comments,
					page:page,
					isnodata:isnodata,
					loading:false,
				});
			}
			
		});
	},
	change_address:function(e){
		var page=this
		var pagedata = page.data.pagedata
		pagedata.address.id = e.currentTarget.dataset.id;
		var page=this
		page.setData({
				pagedata:pagedata
		});
	},
	showhuodong:function(){
		var page=this
		var showhuodong = page.data.showhuodong
		page.setData({
				showhuodong:!showhuodong
		});
	},
	commentsshowtype:function(){
		var the=this
		the.getcomments();
		the.setData({
				showtype:3
		});
	},
	show_bigimage:function(e){
		var the=this
		var img=e.currentTarget.dataset.img;
		the.setData({
			'pagedata.show_bigimage':!the.data.pagedata.show_bigimage,
			'pagedata.showimage':img
		});
	},
	showsharecover:function(){
		var the=this
		the.setData({
				showsharecover:!the.data.showsharecover
		});
	},
	showsharecode:function(){
		var the=this
		the.setData({
				showsharecode:!the.data.showsharecode
		});
	},
	copylink:function(){
		var the=this
		var pagedata=the.data.pagedata
		wx.setClipboardData({
		  data: pagedata.sharedata.link,
		  success (res) {
			console.log(res) // data
		  }
		})
	},
	modal_address:function(){
		var page=this
		var modal_address = page.data.modal_address
		page.setData({
				modal_address:!modal_address
		});
	},
	edit_address:function(e){
		var the =this
		var data = e.currentTarget.dataset;
		var pagedata = the.data.pagedata
		the.setData({
			modal_address:false,
			edit_address:true
		})
		//获取区域城市
		qqmapsdk = new QQMapWX({
            key: 'SN2BZ-MKT32-22SU7-COVX6-ZYXAQ-OEF6D'
        });
		app.util.location(function(res){
			qqmapsdk.reverseGeocoder({
					location:{latitude:res.latitude,longitude:res.longitude},
					success:function(res){
						var pcd =the.data.pcd
						if(res.result.address_component.province){
							 pcd[0] = res.result.address_component.province
						}
						if(res.result.address_component.city){
							pcd[1] = res.result.address_component.city
						}
						if(res.result.address_component.district){
							pcd[2] = res.result.address_component.district
						}
						the.setData({
							pcd:pcd,
						})
					}
			});
		});
		pagedata.address=data.index?pagedata.address_list[data.index]:pagedata.address;
		the.setData({
			'pagedata.address':pagedata.address,
		});
	},
	close_address:function(){
		var the =this
		the.setData({
			edit_address:false
		})
	},
	post_address:function(e){
		var the =this
		var data=e.detail.value;
		var pagedata=the.data.pagedata
		data.pcd={}
		data.pcd.province=the.data.pcd[0]
		data.pcd.city=the.data.pcd[1]
		data.pcd.district=the.data.pcd[2]
		data.id=pagedata.address.id?pagedata.address.id:'';
		data.get=1
		app.util.post('core/member.address/post/',data,function(res){
			if(res){
				pagedata.post.addressid=data.id?data.id:res;
				if(!data.id){
					pagedata.address_list=pagedata.address_list.concat(data)
				}
				the.setData({
					'pagedata.address_list':pagedata.address_list,
					'pagedata.post':pagedata.post,
					edit_address:false,
					'pagedata.address':data
				});
				app.util.msg('保存成功');	
			}else{
				app.util.msg('保存失败');	
			}
			
		});
	},
	showspec:function(){
		var page=this
		var showspec = page.data.showspec
		page.setData({
				showspec:!showspec
		});
	},
	setvideo:function(e){
		var page=this
		var type = e.currentTarget.dataset.type;
		page.setData({
				'pagedata.isvideo':type
		});
	},
	minus:function(){
		var page=this
		var pagedata = page.data.pagedata
		if(pagedata.post.num <=1){
			app.util.msg('不能再减了','error');
		}else{
			pagedata.post.num--;
			page.setData({
				pagedata:pagedata
			});
		}
		
	},
	plus:function(){
		var page=this
		var pagedata = page.data.pagedata
		pagedata.post.num++;
		if(pagedata.goods.usermaxbuy>0 && pagedata.goods.order_goodscount + pagedata.post.num>=pagedata.goods.usermaxbuy){
			app.util.msg('不能再加了，超过该商品最大购买量！','error');
			return false;
		}
		if(pagedata.goods.maxbuy>0 && pagedata.post.num>=pagedata.goods.maxbuy){
			app.util.msg('不能再加了，超过该商品单次购买量！','error');
			return false;
		}
		if(pagedata.post.num>=pagedata.options.stock){
			app.util.msg('不能再加了，超了库存啦！','error');
			return false;
		}
			page.setData({
				pagedata:pagedata
			});
	},
	setlike:function(){
		var the=this
		var pagedata = the.data.pagedata
		pagedata.islike = !pagedata.islike;		
		the.setData({
				'pagedata.islike':pagedata.islike
		});
		app.util.get('jy_weishop/goods.detail/like/',function(){
			if(pagedata.islike){
				app.util.msg('关注成功');
			}else{
				app.util.msg('关注失败');
			}
		});
	},
	addtocart:function(){
		var the=this
		var pagedata = the.data.pagedata
		pagedata.cartCount ++;
		the.setData({
				pagedata:pagedata,
				showspec:false,
		});
		app.util.post('jy_weishop/goods.detail/addtocart/',{'goodsid':pagedata.post.goodsid,'num':pagedata.post.num,'specid':pagedata.post.specid});
	},
	get_optionsid:function(e){
		var page=this
		var k=e.currentTarget.dataset.key;
		var item = e.currentTarget.dataset.item;
		var pagedata = page.data.pagedata
		pagedata.post.specid[k] = item;
		var specid = pagedata.post.specid;
		specid = specid.join('_');
		app.util.post('jy_weishop/goods.detail/get_optionsid/',{'specid':specid},function(res){
			pagedata.post.optionsid=res.options.id;
			pagedata.options=res.options;
			pagedata.selespename=res.selespename;
			page.setData({
				pagedata:pagedata
			});
		});
		
	},
	num:function(num) {
		return num < 10 ? `0${num}` : `${num}`;
	},
	endDown:function(rest_time) {
		var the=this;
		var pagedata = the.data.pagedata
		var sys_second = rest_time;
		//console.log(rest_time)
		var countDown = the.data.countDown
		clearInterval(the.data.countInterval);
		the.data.countInterval = setInterval(() => {
			sys_second -= 1;
			if (sys_second <= 0) {
				clearInterval(the.data.countInterval);
				the.getactive();
			}
			
			let day = 0;
			let hour = 0;
			let minute = 0;
			let second = 0;

			const DMS = 24 * 60 * 60;
			day = the.num(Math.floor(sys_second / DMS));
			//console.log('day');console.log(day);
			const h1 = sys_second / 3600;
			const h2 = day * 24;
			hour = the.num(Math.floor(h1 - h2));

			const m1 = sys_second / 60;
			const m2 = day * 24 * 60;
			const m3 = hour * 60;
			minute = the.num(Math.floor(m1 - m2 - m3));

			const s1 = day * 24 * 3600;
			const s2 = hour * 3600;
			const s3 = minute * 60;
			second = the.num(Math.floor(sys_second - s1 - s2 - s3));
			  
			countDown = {}
			countDown.hour = hour
			countDown.minute = minute
			countDown.second = second
			the.setData({
				countDown : countDown
			});
			if (sys_second < 0) {
				clearInterval(the.data.countInterval);
				countDown.day = '00'
				countDown.hour = '00'
				countDown.minute = '00'
				countDown.second = '00'
				the.setData({
				  countInterval:null,
				  countDown: countDown
				});
			}
		}, 1000);
	},
	goback: function() {
		var pages=getCurrentPages()
		if(pages.length>1){
			wx.navigateBack({
				'delta':1,
				'fail':function(){
					//console.log('333');
					app.util['access'](app.plugin_name+'/index/');
				},
			})
		}else{
			app.util['access'](app.plugin_name+'/index/');
		}
    },
	check_buy:function(){
		var pagedata=this.data.pagedata
		app.util.get('jy_weishop/goods.detail/check_buy/num='+pagedata.post.num+'&optionsid='+pagedata.post.optionsid+'&addressid='+pagedata.post.addressid+'&storeid='+pagedata.post.storeid);
	},
	showmore_stores:function(){
		var page=this
		page.setData({
			'pagedata.showmore_stores':true
		});
	},
	select_store:function(e){
		var page=this
		var pagedata=page.data.pagedata
		var data=e.currentTarget.dataset;
		pagedata.post.storeid=data.id
		page.setData({
				'pagedata.post':pagedata.post
		});
	},
  	click:function(evt){
		//用户点击事件 data.func 为方法名，data.params 为调用参数！
		var data=evt.currentTarget.dataset;
		app.util[data.func](data.params);
	},
	formSubmit:function(event){
		var data=event.detail.value;
		app.util.post('jy_weishop/goods.detail/post/',data);
	},
	votestrlen:function(str){
		var len = 0;
		for (var i=0; i<str.length; i++) { 
		 var c = str.charCodeAt(i); 
		//单字节加1 
		 if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) { 
		   len++; 
		 } 
		 else { 
		  len+=2; 
		 } 
		} 
		return len;
	},
	showshareall: function(){
			var the=this;
			the.setData({
				showshareall:true
			})
	},
	closeshareall: function(){
			var the=this;
			the.setData({
				showshareall:false,
				showposter:false
			})
	},
	showposter: function(){
			var the=this;
			the.setData({
				showposter:true
			})
	},
	//画布 
	promisify: api => {
		return (options, ...params) => {
		  return new Promise((resolve, reject) => {
			const extras = {
			  success: resolve,
			  fail: reject
			}
			api({ ...options, ...extras }, ...params)
		  })
		}
	},
	GetImagetmp: function(e){
		var the=this;
		var pagedata=e
		var att_url=the.data.att_url
		const wxGetImageInfo = the.promisify(wx.getImageInfo)
		pagedata.member.avatar=pagedata.member.avatar?pagedata.member.avatar:att_url+'../core/resource/images/nopic.jpg'
		pagedata.goods.appcode=pagedata.goods.appcode?pagedata.goods.appcode:'../core/resource/images/nopic.jpg'
		pagedata.goods.image=pagedata.goods.image?pagedata.goods.image:att_url+'../core/resource/images/nopic.jpg'
		Promise.all([
			// 商品图
			wxGetImageInfo({
				src: pagedata.goods.image
			}),
			// 二维码
			wxGetImageInfo({
				src: att_url+pagedata.goods.appcode
			}),
			// 头像
			wxGetImageInfo({
				src: pagedata.member.avatar
			}),
		]).then(res => {
			app.imagetmps=res
			the.setData({
				showgoqrcode:true
			})
		});
	},
	closesetqrcode: function(){
			var the=this;
			the.setData({
				showsetqrcode:false
			})
	},
	share_canvas: function(){
			var the=this;
			if(app.imagetmps){
				app.util.showLoading();
			}else{
				app.util.msg('绘图忙碌,请稍后尝试！');
				return false;
			}
			setTimeout(function(){the.CanvasContext()},500);
	},
	//绘制画
	CanvasContext: function(){
			var the=this;
			var pagedata=the.data.pagedata
			var att_url=the.data.att_url
			var screenWidth=280
			var screenHeight=app.screenHeight * 0.94
			var titleHight=19
			pagedata.member.nickname=pagedata.member.nickname?pagedata.member.nickname:'匿名用户';
			const ctx = wx.createCanvasContext('shareCanvas')
			ctx.setFillStyle('white');//填充白色
			ctx.fillRect(0, 0, screenWidth , 390);//画出矩形白色背景
			ctx.restore();
			// 文字1
			//ctx.setTextAlign('center')    // 文字居中
			ctx.setFillStyle('#000000')  // 文字颜色：黑色
			ctx.setFontSize(12)         // 文字字号：px
			//ctx.fillText(pagedata.member.nickname+' ', 60, 25)
			// 文字2
			//ctx.fillText(pagedata.member.time+'推荐了一款商品', 60, 25 + 19)
			// 商品标题
			ctx.fillText(pagedata.goods.title1+' ', 10,  308)
			ctx.fillText(pagedata.goods.title2+' ', 10,  328)
			ctx.setFillStyle('red')  // 文字颜色：黑色
			ctx.setFontSize(16)         // 文字字号：px
			ctx.fillText('￥'+pagedata.goods.price, 10,  355)
			// 二维码文字
			ctx.setFillStyle('#999')  // 文字颜色：黑色
			//ctx.fillText('扫《'+app.setting.title+'》二维码', screenWidth-270,  295)
			// 二维码文字
			ctx.setFontSize(10)         // 文字字号：px
			ctx.fillText('微信扫一扫', screenWidth-70, 373)
			// 小程序码
			ctx.drawImage(app.imagetmps[1].path, screenWidth-80, 290, 70, 70)
			// 商品图
			ctx.drawImage(app.imagetmps[0].path, 2, 2, screenWidth-4,280)
			// 头像
			//ctx.save()
			//ctx.beginPath()
			//ctx.arc(30, 30, 20, 0,2 * Math.PI);
			//ctx.clip();
			//ctx.setStrokeStyle('#fff');
			//ctx.drawImage(app.imagetmps[2].path,10,5,60,60)
			ctx.restore();
			ctx.draw()
			the.setData({
				showsetqrcode:true
			})
			the.getcanvasToPath()
	},
	//获取海报路径
	getcanvasToPath:function(){
		var the = this;
		var screenWidth=280
		var screenHeight=390
		setTimeout(function () {
			wx.canvasToTempFilePath({
				x: 0,
				y: 0,
				width: screenWidth,
				height: screenHeight,
				destWidth: screenWidth*2.6,
				destHeight: screenHeight*2.6,
				canvasId: 'shareCanvas',
				success: function (res) {
					setTimeout(function () {app.util.hideLoading()},1000);
					the.setData({
						savedImgUrl: res.tempFilePath
					})
				},
				fail: function (res){
					console.log('失败');console.log(res)
					setTimeout(function () {app.util.hideLoading()},1000);
				}
			})
		}, 1000)
	},
	//保存海报
	saveImageToPhoto: function () {
		var that = this;
		setTimeout(function () {
			wx.getImageInfo({
			  src: that.data.pagedata.posterimg,
			  success (res) {
				if (that.data.pagedata.posterimg) {
					wx.saveImageToPhotosAlbum({
						filePath: res.path,
						//filePath:'/resource/images/share-bg01.png',
						success: function () {
							wx.showModal({
								title: '保存图片成功',
								content: '图片已经保存到相册，快去分享吧！',
								showCancel: false,
								success: function (res) {
									that.setData({
										showsetqrcode:false,
										canvasShow: false,
									})
								},
								fail: function (res) { },
									complete: function (res) { },
							});
						},
						fail: function(res) {
							//console.log(res);
							if (res.errMsg == "saveImageToPhotosAlbum:fail cancel") {
								wx.showModal({
									title: '保存图片失败',
									content: '您已取消保存图片到相册！',
									showCancel: false
								});
							} else {
								wx.showModal({
									title: '提示',
									content: '保存图片失败，您可以点击确定设置获取相册权限后再尝试保存！',
									complete: function(res) {
										//console.log(res);
										if (res.confirm) {
										wx.openSetting({}) //打开小程序设置页面，可以设置权限
										} else {
										wx.showModal({
											title: '保存图片失败',
											content: '您已取消保存图片到相册！',
											showCancel: false
										});
										}
									}
								});
							}
						}
					})
				}
			  }
			});
		}, 500)
	},
	onShareAppMessage: function (res) {
		var the = this
		var pagedata = the.data.pagedata
		if (res.from === 'button') {
		}
		if(!pagedata.goods){
			return false;
		}
		var path=the.data.route+'?id='+pagedata.goods.id;
		if(app.access.op){
			path +='&op='+app.access.op;
		}
		if(pagedata.fromuser){
			path +='&fromuser='+pagedata.fromuser;
		}
		var title=pagedata.goods.title+' ￥'+pagedata.goods.price+'/'+pagedata.goods.unit;
		title=pagedata.goods.active.title?'【'+pagedata.goods.active.title+'】'+title:title;
		return {
		  title: title,
		  path: path,
		  desc: app.setting.sharedesc,
		  imageUrl: pagedata.goods.image,
		  success: function(res) {
		  },
		  fail: function(res) {
		  }
		}
	},
	onShareTimeline: function (res) {
		var the = this
		var pagedata = the.data.pagedata
		var query=app.access.query
		if(app.access.op){
			query +='&op='+app.access.op;
		}
		if(pagedata.fromuser){
			query +='&fromuser='+pagedata.fromuser;
		}
		query +='&isgoshare=1'
		var title=pagedata.goods.title+' ￥'+pagedata.goods.price+'/'+pagedata.goods.unit;
		title=pagedata.goods.active.title?'【'+pagedata.goods.active.title+'】'+title:title;
		return {
		  title: title,
		  query: query,
		  desc: app.setting.sharedesc,
		  imageUrl: pagedata.goods.image,
		  success: function(res) {
		  },
		  fail: function(res) {
		  }
		}
	},
});